<script setup>
import { ref, onMounted } from 'vue'
import axios from '@/utils/axios'
import ProductCard from './ProductCard.vue'
import { ElMessage } from 'element-plus'

const products = ref([])
const loading = ref(true)
const error = ref(null)
const baseURL = import.meta.env.VITE_API_URL || 'http://localhost:5000'

const fetchProducts = async () => {
  try {
    loading.value = true
    console.log('Fetching hot products...')
    
    let response
    try {
      response = await axios.get('/api/products/hot')
      console.log('Raw API response:', response)
    } catch (err) {
      console.error('API request failed:', err)
      throw new Error(err.response?.data?.message || '请求失败，请稍后重试')
    }

    if (!response?.data) {
      console.error('No response data')
      throw new Error('服务器返回数据为空')
    }

    const { success, data, message } = response.data
    console.log('Response data:', { success, data, message })

    if (!success) {
      throw new Error(message || '获取数据失败')
    }

    if (!Array.isArray(data)) {
      console.error('Invalid data format:', data)
      throw new Error('数据格式错误')
    }

    products.value = data.map(product => {
      if (!product) {
        console.warn('Empty product object found')
        return null
      }
      
      try {
        const processedProduct = {
          id: product.id || 0,
          name: product.name || '',
          description: product.description || '',
          price: Number(product.price || 0),
          image: product.image?.startsWith('http') 
            ? product.image 
            : `${baseURL}/uploads/${product.image?.replace(/^\/uploads\//, '') || 'default.png'}`,
          avg_rating: product.avg_rating || '0.0',
          review_count: Number(product.review_count || 0),
          sales: Number(product.sales || 0)
        }
        console.log('Processed product:', processedProduct)
        return processedProduct
      } catch (err) {
        console.error('Error processing product:', err, product)
        return null
      }
    }).filter(Boolean) // 移除空值

    console.log('Final processed products:', products.value)
  } catch (err) {
    console.error('Error fetching hot products:', err)
    error.value = err
    ElMessage.error(err.message || '获取热门商品失败')
    products.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<template>
  <div class="hot-products">
    <div v-if="loading" class="loading">
      <el-skeleton :rows="3" animated />
    </div>
    <div v-else-if="error" class="error">
      <el-alert
        title="加载失败"
        type="error"
        :description="error.message"
        show-icon
      />
    </div>
    <div v-else-if="products.length === 0" class="empty">
      <el-empty description="暂无热门商品" />
    </div>
    <div v-else class="products-grid">
      <ProductCard 
        v-for="product in products" 
        :key="product.id" 
        :product="product"
      />
    </div>
  </div>
</template>

<style scoped>
.hot-products {
  margin: 20px 0;
}

.loading {
  padding: 20px;
}

.error {
  margin: 20px 0;
}

.empty {
  padding: 40px 0;
  text-align: center;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 10px;
  }
}
</style> 